package com.sise.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sise.bean.CodeMsg;
import com.sise.entity.Admin;
import com.sise.mapper.AdminMapper;
import com.sise.service.IAdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author zj
 */
@Slf4j
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    @Resource
    private AdminMapper adminMapper;

    @Override
    public ModelAndView login(Admin admin) {
        ModelAndView modelAndView = new ModelAndView();
        String md5Password = md5Check(admin.getAdminPassword());
        QueryWrapper<Admin> adminQueryWrapper = new QueryWrapper<>();
        adminQueryWrapper.lambda().eq(Admin::getAdminAccount, admin.getAdminAccount()).eq(Admin::getAdminPassword, md5Password);
        Admin getAdmin = adminMapper.selectOne(adminQueryWrapper);
        String view = "login";
        if (getAdmin != null) {
            modelAndView.addObject("username", getAdmin.getAdminAccount());
            view = "index";
        } else {
            modelAndView.addObject("msg", "用户名或密码错误");
        }
        modelAndView.setViewName(view);
        return modelAndView;
    }

    @Override
    public CodeMsg weblogin(Admin admin) {
        String md5Password = md5Check(admin.getAdminPassword());
        QueryWrapper<Admin> adminQueryWrapper = new QueryWrapper<>();
        adminQueryWrapper.lambda().eq(Admin::getAdminAccount, admin.getAdminAccount()).eq(Admin::getAdminPassword, md5Password);
        Admin getAdmin = adminMapper.selectOne(adminQueryWrapper);
        CodeMsg<Admin> codeMsg = new CodeMsg<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String format = formatter.format(LocalDateTime.now());
        String team;
        if (getAdmin != null) {
            team = "登录成功";
            codeMsg.setCode(200).setData(getAdmin.setAdminPassword(null));
            admin.setAdminId(getAdmin.getAdminId()).setLoginTime(format).setAdminPassword(md5Password);
            adminMapper.updateById(admin);
        } else {
            team = "用户名或密码错误";
            codeMsg.setCode(400);
        }
        codeMsg.setMsg(team);
        log.info("登录信息---用户名：" + admin.getAdminAccount() + " ，登录时间：" + format + " ，登录IP：" + admin.getLoginIp() +
                " ，登录地点" + admin.getLoginLocale() + " ，状态：" + team);
        return codeMsg;
    }

    @Override
    public CodeMsg changePassword(Admin admin, String password) {
        QueryWrapper<Admin> adminQueryWrapper = new QueryWrapper<>();
        adminQueryWrapper.lambda().eq(Admin::getAdminAccount, admin.getAdminAccount())
                .eq(Admin::getAdminPassword, DigestUtils.md5DigestAsHex(admin.getAdminPassword().getBytes()));
        Admin getAdmin = adminMapper.selectOne(adminQueryWrapper);
        if (getAdmin != null) {
            getAdmin.setAdminPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
            adminMapper.updateById(getAdmin);
            return new CodeMsg().setCode(200).setMsg("修改成功");
        } else {
            return new CodeMsg().setCode(400).setMsg("原密码错误");
        }
    }

    @Override
    public CodeMsg permissionVerification(Admin admin) {
        QueryWrapper<Admin> adminQueryWrapper = new QueryWrapper<>();
        adminQueryWrapper.lambda().eq(Admin::getAdminId, admin.getAdminId())
                .eq(Admin::getAdminAccount, admin.getAdminAccount());
        Admin getAdmin = adminMapper.selectOne(adminQueryWrapper);
        if (getAdmin != null) {
            if ("admin".equals(getAdmin.getAdminPermission()) ||
                    "root".equals(getAdmin.getAdminPermission())) {
                return new CodeMsg().setCode(200).setMsg("验证成功");
            } else {
                return new CodeMsg().setCode(401).setMsg("权限不足");
            }
        } else {
            return new CodeMsg().setCode(400).setMsg("验证错误");
        }
    }

    @Override
    public CodeMsg getAllAdmin(Admin admin) {
        QueryWrapper<Admin> adminQueryWrapper = new QueryWrapper<>();
        adminQueryWrapper.lambda().eq(Admin::getAdminId, admin.getAdminId())
                .eq(Admin::getAdminAccount, admin.getAdminAccount())
                .eq(Admin::getAdminPermission, admin.getAdminPermission());
        Admin getAdmin = adminMapper.selectOne(adminQueryWrapper);
        if (getAdmin != null) {
            List<Admin> adminList = adminMapper.selectList(null);
            adminList.forEach(i -> i.setAdminPassword(null));
            return new CodeMsg().setCode(200).setData(adminList);
        } else {
            return new CodeMsg().setCode(400).setMsg("用户不存在");
        }
    }

    @Override
    public CodeMsg deleteAdminById(Integer userId, Integer deleteId) {
        if (userId.equals(deleteId)) {
            return new CodeMsg().setCode(400).setMsg("不可以删除自己的账号");
        }
        Admin admin = adminMapper.selectById(userId);
        if (admin != null) {
            if ("root".equals(admin.getAdminPermission())) {
                Admin getAdmin = adminMapper.selectById(deleteId);
                if (getAdmin != null) {
                    int tap = adminMapper.deleteById(getAdmin);
                    if (tap == 1) {
                        return new CodeMsg().setCode(200).setMsg("删除成功");
                    } else {
                        return new CodeMsg().setCode(400).setMsg("删除失败");
                    }
                } else {
                    return new CodeMsg().setCode(400).setMsg("删除的用户不存在");
                }
            } else {
                return new CodeMsg().setCode(400).setMsg("只能使用最高权限用户删除");
            }
        } else {
            return new CodeMsg().setCode(400).setMsg("用户不存在，删除失败");
        }
    }

    @Override
    public CodeMsg addAdmin(Integer userId, String adminAccount) {
        if ("".equals(adminAccount)) {
            return new CodeMsg().setCode(400).setMsg("用户账户不允许为空，添加失败");
        }
        Admin admin = adminMapper.selectById(userId);
        if (admin != null) {
            QueryWrapper<Admin> adminQueryWrapper = new QueryWrapper<>();
            adminQueryWrapper.lambda().eq(Admin::getAdminAccount, adminAccount);
            Admin getAdmin = adminMapper.selectOne(adminQueryWrapper);
            if (getAdmin != null) {
                return new CodeMsg().setCode(400).setMsg("用户已存在，添加失败");
            }
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String format = formatter.format(LocalDateTime.now());
            Admin addAdmin = new Admin().setAdminAccount(adminAccount)
                    .setAdminPassword(DigestUtils.md5DigestAsHex("123456".getBytes()))
                    .setLoginTime(format)
                    .setLoginIp("new admin")
                    .setLoginLocale("new admin");
            if ("root".equals(admin.getAdminPermission())) {
                addAdmin.setAdminPermission("admin");
            } else if ("admin".equals(admin.getAdminPermission())) {
                addAdmin.setAdminPermission("user");
            } else {
                return new CodeMsg().setCode(400).setMsg("用户权限不足，添加失败");
            }
            int tap = adminMapper.insert(addAdmin);
            if (tap == 1) {
                return new CodeMsg().setCode(200).setMsg("用户添加成功，初始化密码：123456，请及时修改密码");
            } else {
                return new CodeMsg().setCode(400).setMsg("用户添加失败");
            }
        } else {
            return new CodeMsg().setCode(400).setMsg("用户不存在，添加失败");
        }
    }

    @Override
    public CodeMsg resetAdminById(Integer userId, Integer resetId) {
        if (userId.equals(resetId)) {
            return new CodeMsg().setCode(400).setMsg("不可以重置自己的密码");
        }
        Admin admin = adminMapper.selectById(userId);
        if (admin != null) {
            if ("root".equals(admin.getAdminPermission())) {
                Admin getAdmin = adminMapper.selectById(resetId);
                if (getAdmin != null) {
                    getAdmin.setAdminPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
                    int tap = adminMapper.updateById(getAdmin);
                    if (tap == 1) {
                        return new CodeMsg().setCode(200).setMsg("重置成功，初始化密码：123456，请及时修改密码");
                    } else {
                        return new CodeMsg().setCode(400).setMsg("重置失败");
                    }
                } else {
                    return new CodeMsg().setCode(400).setMsg("重置的用户不存在");
                }
            } else {
                return new CodeMsg().setCode(400).setMsg("只能使用最高权限用户重置");
            }
        } else {
            return new CodeMsg().setCode(400).setMsg("用户不存在，重置失败");
        }
    }

    @Override
    public CodeMsg oneClickReset(Integer[] operationIdList, Integer userId) {
        Admin admin = adminMapper.selectById(userId);
        if (admin != null) {
            if ("root".equals(admin.getAdminPermission())) {
                String msg = "";
                for (Integer resetId : operationIdList) {
                    if (userId.equals(resetId)) {
                        msg = "，已跳过最高权限密码重置";
                        continue;
                    }
                    Admin getAdmin = adminMapper.selectById(resetId);
                    if (getAdmin != null) {
                        getAdmin.setAdminPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
                        adminMapper.updateById(getAdmin);
                    }
                }
                return new CodeMsg().setCode(200).setMsg("重置成功，初始化密码：123456，请及时修改密码" + msg);
            } else {
                return new CodeMsg().setCode(400).setMsg("只能使用最高权限用户重置");
            }
        } else {
            return new CodeMsg().setCode(400).setMsg("用户不存在，重置失败");
        }
    }

    @Override
    public CodeMsg oneClickDelete(Integer[] operationIdList, Integer userId) {
        Admin admin = adminMapper.selectById(userId);
        if (admin != null) {
            if ("root".equals(admin.getAdminPermission())) {
                String msg = "";
                for (Integer deleteId : operationIdList) {
                    if (userId.equals(deleteId)) {
                        msg = "，已跳过删除最高权限用户";
                        continue;
                    }
                    Admin getAdmin = adminMapper.selectById(deleteId);
                    if (getAdmin != null) {
                        adminMapper.deleteById(getAdmin);
                    }
                }
                return new CodeMsg().setCode(200).setMsg("删除成功" + msg);
            } else {
                return new CodeMsg().setCode(400).setMsg("只能使用最高权限用户删除");
            }
        } else {
            return new CodeMsg().setCode(400).setMsg("用户不存在，删除失败");
        }
    }

    /**
     * 将字符串转用md5加密
     */
    public String md5Check(String value) {
        return DigestUtils.md5DigestAsHex(value.getBytes());
    }
}
